package cat.music.ut.viewmodel

import android.util.Log
import androidx.lifecycle.MutableLiveData
import cat.music.ut.bean.AudioInfo
import cat.music.ut.bean.SearchResult
import cat.music.ut.bean.parseAudioInfo
import cat.music.ut.comm.http.OkHttpUtil
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject

class DownloadViewModel : BaseViewModel() {
    val mldDownloadUrl = MutableLiveData<AudioInfo?>()
    fun download(audioInfo: AudioInfo,searchResult: SearchResult) {
        coroutinesHttp {
            val url = "https://mobi.kuwo.cn/mobi.s?f=web&type=&type=convert_url_with_sign&source=kwplayer_ar_4.4.2.7_B_nuoweida_vh.apk&rid=" +
                    "${searchResult.id.replace("MUSIC_","")}&format=${audioInfo.format}&br=${audioInfo.bitrate}k${audioInfo.format}"
            val str = OkHttpUtil.get(url)
            Log.e(">>", "search: $str" )
            runCatching {
                audioInfo.url = JSON.parseObject(str).getJSONObject("data").getString("url")
                mldDownloadUrl.postValue(audioInfo)
            }.getOrElse {
                mldDownloadUrl.postValue(null)
            }
        }
    }
}